const imgStore = {};
const timeArr = [];
const maxNum = 300; //最多存300张

const observe = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      handleFun(entry.target, entry.target.binding);
      observe.unobserve(entry.target);
    }
  });
});
function handleFun(el, binding) {
  if (imgStore[binding.value]) {
    el.setAttribute("data-load", "end");
    el.src = imgStore[binding.value];
    return;
  }
  el.setAttribute("data-load", "loading");
  el.src = "/favicon.ico";
  el.controller = new AbortController();
  let a = Math.random();
  console.time(a);
  fetch(`${binding.value}`, {
    signal: el.controller.signal,
  })
    .then((response) => response.blob())
    .then((blob) => {
      const url = URL.createObjectURL(blob);
      if (timeArr.length > maxNum) {
        let value = timeArr.shift();
        delete imgStore[value];
      } else {
        imgStore[binding.value] = url;
        timeArr.push(binding.value);
      }

      el.src = url;
      el.setAttribute("data-load", "end");
      console.timeEnd(a);
    })
    .catch((error) => {});
}

export default {
  inserted(el, binding) {
    el.binding = binding;
    observe.observe(el);
  },
  update(el, binding) {
    el.controller && el.controller.abort();
    el.binding = binding;
    observe.observe(el);
  },
  unbind(el) {
    observe.unobserve(el);
    el.controller && el.controller.abort();
  },
};
